<?php

class Logger extends PrspLibrary{
	
	private static $debugMsg = Array();
	private static $enabled = true;
	private static $level = 0;
	private static $show = false;

	public function initial(){}
	
	public function getSelfPluginId(){
		$pluginId = str_replace(PLUGINS_PATH, '', __FILE__);
		return substr($pluginId,1,strpos($pluginId, '/', 2)-1);
	}
	
	private function addMessage($type, $msg){
		//TODO Level Filter
		if(Logger::$enabled){
			$array = debug_backtrace();
			$file = substr($array[1]['file'], strrpos($array[1]['file'],'/')+1);
			$line = $array[1]['line'];
			$log['type'] = $type;
			$log['msg'] = $msg." - $file ($line)";
			$log['time'] = date("H:i:s.").substr(microtime(),2,3);
			if( array_key_exists( Runtime::getPluginId(), Register::getPlugins() ) ){
				$plugins = Register::getPlugins();
				$log['pluginId'] = Runtime::getPluginId();
				$log['version'] = $plugins[Runtime::getPluginId()]['Version'];
			}
			Logger::$debugMsg[] = $log;
			if(Logger::$show){
				echo "$msg<br />";
			}
		}
	}
	
	/**
	 * 設定是否啟用 Debugger
	 * @param unknown_type $enabled
	 */
	public static function setEnabled($enabled) {
		Logger::$enabled = $enabled;
	}

	/**
	 * 取得是否開啟記錄
	 * @return unknown
	 */
	public static function isEnabled () {
		return Logger::$enabled;
	}

	/**
	 * 設定 Level
	 *
	 * @param unknown_type $level
	 */
	public static function setLevel($level) {
		Logger::$level = $level;
	}
	
	public function error($msg){
		Logger::addMessage('ERROR', $msg);
	}
	
	public function fail($msg){
		Logger::addMessage('FAIL', $msg);
	}
	
	public function warn($msg){
		Logger::addMessage('WARN', $msg);
	}
	
	public function info($msg){
		Logger::addMessage('INFO', $msg);
	}
	
	public function debug($msg){
		Logger::addMessage('DEBUG', $msg);
	}
	
	public function sql($msg){
		Logger::addMessage('SQL', $msg);
	}
	
	public function getMsg($plugin=null){
		if($plugin==null){
			return Logger::$debugMsg;
		}else{
			$rtnList = array();
			foreach ( Logger::$debugMsg as $logger ){
				if($plugin===$logger['pluginId']){
					array_push($rtnList, $logger );
				}
			}
			return $rtnList;
		}
	}
	
	public function show(){
		if( Logger::$enabled ){
			echo '<table border="1">';
			echo '<tr><th>Message</th></tr>';
			foreach ( Logger::$debugMsg as $logger ){
				echo '<tr><td>'.$logger['msg'].'</td></tr>';
			}
			echo '</table>';
		}
	}
	
}

?>